package com.studentbook.servlet;

import com.studentbook.service.StudentContactService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 保存通讯录信息到文件Servlet
 */
@WebServlet("/saveContactsToFile")
public class SaveContactsToFileServlet extends HttpServlet {
    private StudentContactService contactService = new StudentContactService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取文件路径参数（可选）
        String filePath = request.getParameter("filePath");
        
        try {
            // 保存通讯录信息到文件
            boolean success = contactService.saveContactsToFile(filePath);
            
            if (success) {
                // 保存成功
                request.setAttribute("message", "成功将联系人信息保存到文件！");
            } else {
                // 保存失败
                request.setAttribute("message", "保存联系人信息到文件失败！");
            }
            
            // 转发到联系人列表页面
            request.getRequestDispatcher("/listContacts").forward(request, response);
        } catch (Exception e) {
            // 处理异常
            request.setAttribute("message", "保存联系人信息到文件失败：" + e.getMessage());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}